﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TMScore_Subsets
{
    // this class is responsible for generating TMScore for a subset of documents
    class SubsetsTMScoreGenerator
    {

        /// <summary>
        /// This is the main method, which computes the TMScore for a subset of documents, according to the algorithm
        /// developed in the research
        /// </summary>
        public double GetTMScore (List<Document> Documents)
        {

            if (Documents == null || Documents.Count == 0)
                return 0;

            Documents = Documents.OrderByDescending(x => x.Fingerprints.Count).ToList(); // sorting the documents by their length
            //Documents.Reverse();
           

            double tmscore = Documents[0].TMScore;
            HashSet<int> totalFP = new HashSet<int>(Documents[0].Fingerprints.Keys);
            HashSet<int> currentDocFP; 

            for (int i = 1; i < Documents.Count; i++)
            {
                currentDocFP = new HashSet<int>(Documents[i].Fingerprints.Keys);
                tmscore += (double)(1 - Overlap(totalFP, currentDocFP)) * Documents[i].TMScore;
                totalFP.UnionWith(currentDocFP);
            }

            return Math.Round(tmscore, 5, MidpointRounding.AwayFromZero);
        }


        /// <summary>
        /// computing the overlap percentage between 2 sets of fingerprints, i.e. how many fingerprints of the shorter 
        /// set are found in the longer set, devided in the shorter set's length.
        /// </summary>
        private double Overlap(HashSet<int> longSet, HashSet<int> shortSet)
        {
            int count = 0;

            foreach (int fingerprint in shortSet)
            {
                if (longSet.Contains(fingerprint))
                    count++;
            }

            return (double)count / (double)shortSet.Count;
        }



    }
}
